package com.ruoyi.shop.ai;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.shop.common.utils.AIUtils;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.shop.common.constant.Constants.ACCESS_TOKEN;


/**
 * @Author: JinChen Zhu
 * @CreateTime: 2024-06-28  02:11
 */
@Component
public class AIHelper {
    @Autowired
    private RedisCache redisCache;
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public List<String> abstractPoint(String comment) throws Exception {
        //判断redis中是否存在access_token
        String accessToken = redisCache.getCacheObject(ACCESS_TOKEN);
        if (accessToken == null) {
            accessToken = AIUtils.getAccessToken();
            redisCache.setCacheObject(ACCESS_TOKEN, accessToken);
        }
        String url = "https://aip.baidubce.com/rpc/2.0/nlp/v2/comment_tag?charset=UTF-8&access_token=" + accessToken;
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{\"text\":\"" + comment + "\",\"type\":12}");
        Request request = new Request.Builder().url(url).method("POST", body).addHeader("Content-Type", "application/json").addHeader("Accept", "application/json").build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        // 解析返回的 JSON 对象
        String responseJson = null;
        if (response.body() != null) {
            responseJson = response.body().string();
        }
        JSONObject jsonObject = JSON.parseObject(responseJson);
        // 检查 items 是否存在并为 JSONArray
        if (jsonObject.containsKey("items") && jsonObject.get("items") instanceof JSONArray) {
            JSONArray itemsArray = jsonObject.getJSONArray("items");
            List<String> resultList = new ArrayList<>();
            // 遍历 JSONArray 看看每个元素
            for (int i = 0; i < itemsArray.size(); i++) {
                JSONObject itemObject = itemsArray.getJSONObject(i);
                String propStr = itemObject.getString("prop");
                String adjStr = itemObject.getString("adj");
                String result = propStr + adjStr;
                resultList.add(result);
            }
            // 转成List<String>并返回
            return resultList;
        } else {
            return new ArrayList<>();
        }
    }


}
